package org.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: duk
 * @Date: 2022/1/12 21:46
 * @Description: gateway全局过滤器
 */
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //获取第一个参数
        String token = queryParams.getFirst("token");
        if ("admin".equals(token)){
            //相互匹配，放行进行下一个拦截器执行
            return chain.filter(exchange);
        }
        //不匹配，进行拦截
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码为401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //返回错误信息
        return response.setComplete();
    }
}
